package com.bdqn.petmalldemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.bdqn.petmalldemo.common.ResultCodeEnum;
import com.bdqn.petmalldemo.common.ReturnResult;
import com.bdqn.petmalldemo.common.TokenCache;
import com.bdqn.petmalldemo.entity.Product;
import com.bdqn.petmalldemo.entity.User;
import com.bdqn.petmalldemo.service.IndexService;
import com.bdqn.petmalldemo.service.ProductService;
import com.bdqn.petmalldemo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:彭俊
 * @description:首页控制器
 * @date:2020/2/262048
 */
@Api(tags = "首页控制器")
@RestController
@RequestMapping(value = "/index")
public class IndexController {
    @Autowired
    private ProductService productService;

    @Autowired
    private UserService userService;
    @Autowired
    private IndexService indexService;

    @ApiOperation(value = "热度Top10和推荐数据查询")
    @PostMapping(value = "mall")
    public ReturnResult mall() {
        List<Product> hotTopProduct = productService.hotTopProduct();
        List<Product> recommendProductList = productService.recommendProduct();
        Map<String, Object> map = new HashMap<>(16);
        map.put("hotProductList", hotTopProduct);
        map.put("recommendProductList", recommendProductList);
        return ReturnResult.ok().data(map);
    }

    @ApiOperation(value = "会员中心用户信息查询")
    @PostMapping(value = "/user")
    public ReturnResult getUserInfo(String token){
        //校验token是否有效
        if (StringUtils.isEmpty(token)) {
            return  ReturnResult.error().code(ResultCodeEnum.TOKEN_NULL.getCode())
                    .msg(ResultCodeEnum.TOKEN_NULL.getMsg());
        }
        String jsonUser = TokenCache.get(token);
        if (StringUtils.isEmpty(jsonUser)) {
            return ReturnResult.error().code(ResultCodeEnum.TOKEN_INVALID.getCode())
                    .msg(ResultCodeEnum.TOKEN_INVALID.getMsg());
        }
        User user = JSONObject.parseObject(jsonUser, User.class);
        User userById = userService.getById(user.getId()).setPassword("");
        if (userById==null) {
            return ReturnResult.error().code(ResultCodeEnum.DATA_NULL.getCode())
                    .msg(ResultCodeEnum.DATA_NULL.getMsg());
        }
        Map<String,Object> map = new HashMap<>(16);
        map.put("user",userById);
        return ReturnResult.ok().data(map);
    }


}
